package com.ittx.dzt.tiktok.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.OrderGetDTO;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractBaseTiktokApiHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据取消单号下载退货单
 * <p>
 * cy.returnOrder.download.byOrderId
 * /return_refund/202309/returns/search （售后单查询） https://partner.tiktokshop.com/docv2/page/650ab69edefece02be70785b?external_id=650ab69edefece02be70785b#Back%20To%20Top
 * </p>
 *
 * @author gywang
 * @since 2024-07-23
 */
@Slf4j
@Service
public class TiktokReturnOrderDownloadByIdService extends AbstractBaseTiktokApiHandler<OrderGetDTO> {

	/**
	 * 每页单量
	 */
	public static final int PAGE_SIZE = 50;

	@Override
	public String getTiktokMethod() {
		return TiktokApiConstant.DOWNLOAD_RETURN_DETAIL;
	}

	@Override
	public String getLocalApiMethod() {
		return open.constant.PlatformApiConstant.InboundInterface.RETURNORDER_DOWNLOAD_BY_ORDERID;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		// 售后单ID
		String[] refundIdArray = StringUtils.split(orderGetDTO.getRefundId(), ",");
		List<Object> list = new ArrayList<>();
		if (refundIdArray != null && refundIdArray.length > 0) {
			for (String refundId : refundIdArray) {
				Result<?> result = this.getRefundById(platformApiParamDTO, refundId);
				if (!result.isSuccess()) {
					return result;
				}
				Object refundData = result.getData();
				// 同步返回
				if (orderGetDTO.getIsAsync() == 0) {
					list.add(refundData);
				} else {
					platformApiParamDTO.setPlatformIdentifierTag(refundId);
					result = this.sendRequestToPlatform(platformApiParamDTO, refundData, true);
					if (!result.isSuccess()) {
						return result;
					}
				}
			}
		}
		// 同步返回
		if (orderGetDTO.getIsAsync() == 0) {
			return Result.success().addData(list).addMsg(platformApiParamDTO.getStoreConfig().getChainUniqueCode());
		}
		return Result.success();

	}

	/**
	 * 根据id获取售后单
	 *
	 * @param platformApiParamDTO 平台参数
	 * @param id                  售后单id
	 * @return
	 */
	public Result<?> getRefundById(PlatformApiParamDTO platformApiParamDTO, String id) {
		return this.getRefundBySDK(platformApiParamDTO, id);
	}


	/**
	 * 执行api请求sdk
	 *
	 * @param platformApiParamDTO 平台参数
	 * @param id                  售后单id
	 * @return 请求结果 resultMap.get(DATA_FIELD)
	 */
	public Result<?> getRefundBySDK(PlatformApiParamDTO platformApiParamDTO, String id) {
		Map<String, Object> params = new HashMap<>();
		params.put("shop_cipher", getShopCipher(platformApiParamDTO));
		params.put("page_size", PAGE_SIZE);
		//按page size拆分ids
		Map<String, Object> reqBody = new HashMap<>();
		// 售后Id
		reqBody.put("return_ids", id);
		reqBody.put("locale", "zh-CN");
		Result<?> result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, JacksonTool.toJson(reqBody), platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
		if (result.hasError()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Object refundObj = resultMap.get(DATA_FIELD);
		if (refundObj == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, platformApiParamDTO.getRequestId(), id);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}
		Map<String, Object> refundMap = Convert.toMap(String.class, Object.class, refundObj);
		List returnOrders = MapUtil.get(refundMap, "return_orders", List.class);
		if (CollUtil.isEmpty(returnOrders)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, platformApiParamDTO.getRequestId(), id);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
		}

		return Result.success().addData(refundObj);

	}
}
